﻿<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset = "UTF-8">
    <script src="{{url_for('static',filename='js/jquery.min.js')}}"></script>
    <script src="{{url_for('static',filename='js/clientManage.js')}}?{{ version }}"></script>
    <script src="{{url_for('static',filename='js/bootstrap.min.js')}}"></script>
    <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="{{url_for('static',filename='css/bootstrap.min.css')}}">
    <style>
    .button{
        background-color: white;
        color: black;
        border: 2px solid rgb(68,113,188);
    }

    .button:hover {
        background-color: rgb(68,113,188);
        color: white;
    }

    .button[disabled] {
        opacity: 0.6;
        cursor: not-allowed;
    }

    </style>
    <style>
        .black_overlay{
            display: none;
            position: absolute;
            top: 0%;
            left: 0%;
            width: 100%;
            height: 100%;
            background-color: black;
            z-index:1001;
            -moz-opacity: 0.8;
            opacity:.80;
            filter: alpha(opacity=88);
        }
        .white_content {
            display: none;
            position: absolute;
            top: 5%;
            left: 10%;
            width: 80%;
            height: 20%;
            padding: 20px;
            border: 4px solid rgb(68,113,188);
            background-color: white;
            z-index:1002;
            overflow: auto;
        }
        .white_content_cash {
            display: none;
            position: absolute;
            top: 5%;
            left: 30%;
            width: 30%;
            height: 25%;
            padding: 20px;
            border: 4px solid rgb(68,113,188);
            background-color: white;
            z-index:1002;
            overflow: auto;
        }
    </style>
    <title>客户管理</title>
</head>
<body>
        <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
    <div class="navbar-header">
        <a class="navbar-brand" href="#">盯盘宝后台管理系统</a>
    </div>
    <div>
        <ul class="nav navbar-nav">
            <li ><a href="{{ url_for('start_web') }}">首页</a></li>
            <li ><a href="{{ url_for('permission_manage') }}">权限配置</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
            <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                    管理员{{ session['admin'] if session['admin'] else "未登录" }}
                    <b class="caret"></b>
                </a>
                <ul class="dropdown-menu">
                    <li><a href="{{ url_for("login_out") }}">退出</a></li>
                </ul>
            </li>
        </ul>
    </div>
    </div>
</nav>
        <div id="light" class="white_content">
              <div class="form-group">
                  <label class="col-md-2">请输入需添加策略名:</label>
                  <div class="col-md-10">
                    <input type="text" class="form-control" id="input-strategy-name">
                  </div>
              </div>
            <br/>
            <br/>
            <div class="form-group">
                  <label class="col-md-2">请输入需删除的策略名:</label>
                  <div class="col-md-10">
                    <input type="text" class="form-control" id="delete-strategy-name">
                  </div>
              </div>
            <br/>
            <br/>
<div align="center">

    <div class="btn-group btn-group-lg" role="group" aria-label="...">


        <div class="btn-group" role="group">
        <button type="button" class="btn btn-primary" onclick="addStrategySubmit()">提交</button>
        </div>

        <div class="btn-group" role="group">
        <button type="button" class="btn btn-primary" onclick="addStrategyCancel()">取消</button>
        </div>

    </div>
</div>

        </div>
        <div id="fade" class="black_overlay"></div>
        <div id="light-cash" class="white_content_cash">

        </div>
        <div id="fade-cash" class="black_overlay"></div>
<div id="client_manage" style="margin:auto; width:95%">


    <h3 align="center">客户管理</h3>
        <div class="row" align="center">
    <div class="btn-group" >
          <button id="source-button" type="button" class="btn btn-primary">全部</button>
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <span class="caret"></span>
            <span class="sr-only">Toggle Dropdown</span>
          </button>
          <ul class="dropdown-menu">
            <li><a href="#" onclick="selectSource('全部')">全部</a></li>
            <li><a href="#" onclick="selectSource('正式用户')">正式用户</a></li>
            <li><a href="#" onclick="selectSource('试用用户')">试用用户</a></li>
          </ul>
    </div>
    <div class="btn-group" role="group">
    <button id ="refresh_adapter" type="button" class="btn btn-primary" onclick="refreshAdapter()">强制刷新账户</button>
    </div>
    </div>
    <br/>
    <br/>
    <div class="row" align="center" style="border:1px solid rgb(68, 113, 188);">
    <div id ="user_name_checkbox"  style="width:80%;">

    </div>
        <br/>
    <div align="center">
        <div class="btn-group btn-group-lg" role="group" aria-label="...">
        <div class="btn-group" role="group" align="center">
        <button type="button" class="btn btn-primary" onclick="selectSource('客户')">查询</button>
        </div>
        <div class="btn-group" role="group" align="center">
        <button type="button" class="btn btn-primary" onclick="allIn(true)">全选</button>
        </div>
        <div class="btn-group" role="group" align="center">
        <button type="button" class="btn btn-primary" onclick="allIn(false)">全不选</button>
        </div>
        </div>
    </div>
        <br/>
    </div>
    <br/>
    <div>
        <div style="display:inline-block;">
            <button type="button" class="btn btn-primary" onclick="addClient()">添加客户</button>
        </div>
        <div style="display:inline-block;">
            <button type="button" class="btn btn-primary" onclick="addStrategy()">添加/删除策略</button>
        </div>
        <div style="display:inline-block;">
            <label>用户分组打板<input type="checkbox" id="robot2usergroup_cb" onclick="check_usergroup()" {{ robot2group }} /></label>
        </div>
        <div id="submit" style="position:absolute;left:50%;display:inline-block;">
            <button type="button" class="btn btn-primary" onclick="cancel()">取消添加</button>
        </div>
    </div>

    <br/>
    <br/>
    <div style="margin:auto">

    <div id="clientManageDataTable" class="table table-striped table-bordered" cellspacing="0" width="95%">
    </div>
    </div>

</div>


<script>

    function check_usergroup() {

        $.ajax({
            url: "/user_group",
            async: true,
            type: "POST",
            data: JSON.stringify({ "usergroup": $("#robot2usergroup_cb").is(':checked'), "strategy":"dpb_robot2" }),
            success: function (result) {
                alert(result);
            }
        });
    }

        function refreshAdapter(){
        $("#refresh_adapter").attr("disabled","true");
        setTimeout(function () {
           $("#refresh_adapter").removeAttr("disabled");
        },15000);
        $.ajax({
        url: '/refreshAdapter',
        async:true,
        success:function(result){
            setTimeout(function () {
               refreshData();
            },3000);
            }
        });
    }

    var highRiskTotalCash = "{{ highRiskTotalCash }}";
    var lowRiskTotalCash = "{{ lowRiskTotalCash }}";
    function allIn(flag){
    if (flag){
          $(".user-name-checkbox").each(function (key,value) {
        $(value).prop("checked",true);
        var value = $(value).val();
        console.log(value);
        });
    }else{
        $(".user-name-checkbox").each(function (key,value) {
        $(value).prop("checked",false);
        var value = $(value).val();
        console.log(value);
        });
    }
}

function getSelectUser(inputList) {
    var userNameList = [];
    $(".user-name-checkbox").each(function (key,value) {
        if ($(value).is(':checked')){
            var value = $(value).val();
            userNameList.push(value);
        }
    });
    var outputList=inputList.filter(
        function (item) {
            return (userNameList.indexOf(item["userName"]) > -1);
        });
    return outputList;
}

        function selectSource(type) {
        if (type == "客户"){
            $("#source-button").text("全部");
            var filterResultList = getSelectUser(clientList);
        }else{
            allIn(true);
            $("#source-button").text(type);
            if (type == "全部"){
                var filterResultList = clientList;
            }else{
                var filterResultList = clientList.filter(function (item) {
                return item["useCycle"] == type;
                });
            }
        }

        clientManageDataTable.data(filterResultList, 'code');
    }

        function formatDate(time){
            var date = new Date(time);

            var year = date.getFullYear(),
                month = date.getMonth()+1,//月份是从0开始的
                day = date.getDate(),
                hour = date.getHours(),
                min = date.getMinutes(),
                sec = date.getSeconds();
            var newTime = year + '-' +
                        (month < 10? '0' + month : month) + '-' +
                        (day < 10? '0' + day : day) + ' ' +
                        (hour < 10? '0' + hour : hour) + ':' +
                        (min < 10? '0' + min : min) + ':' +
                        (sec < 10? '0' + sec : sec);

            return newTime;
        }

        function addDate(date,days){
            var d=new Date(date);
            d.setDate(d.getDate()+days);
            var m=d.getMonth()+1;
            return d.getFullYear()+'-'+m+'-'+d.getDate();
        }

        function addClient() {
            var inputList = $(".no-editor");
            if (inputList.length>0){
                return;
            }
            var go = window.confirm("您确定要添加客户吗?")
            if (go == false){
                return;
            }
            window.alert("资产和收益会第二天自动刷新，请填写其他!");
            var tdList = $("#clientManageDataTable").find('table > tbody > tr >td');
            var widthList = [];

            tdList.each(function(key,value){
                var value = $(value).width();
                widthList.push(value);
            });
            var trList = $("#clientManageDataTable").find('table > tbody > tr');
            var trLength = String(trList.length+1);


            var rowStr = jQuery('<tr></tr>');
            var indexHtml = jQuery('<td>' + trLength + '</td>');
            rowStr.append(indexHtml);

            var accountIdWidth = widthList[1];
            var accountIdHtml = jQuery('<td>' +'<input type="text" style="width:'+String(accountIdWidth)+'px;" ' +
                'class="account-id"/>' + '</td>');
            rowStr.append(accountIdHtml);

            var userNameWidth = widthList[2];
            var userNameHtml = jQuery('<td>' +'<input type="text" style="width:'+String(userNameWidth)+'px;" ' +
                'class="user-name"/>' + '</td>');
            rowStr.append(userNameHtml);

            var passwordWidth = widthList[1];
            var passwordHtml = jQuery('<td>' +'<input type="text" style="width:'+String(passwordWidth)+'px;" ' +
                'class="password"/>' + '</td>');
            rowStr.append(passwordHtml);

            var initCapitalHtml = jQuery('<td>0</td>');
            rowStr.append(initCapitalHtml);

            var useCycleWidth = widthList[5];
            var useCycleHtml = '<select class="no-editor" onclick="noEditor()" style="width:'+String(useCycleWidth)+'px;" disabled="disabled">' +
                        '<option value="try">试用用户</option>' +
                        '<option value="year">正式用户</option>' +
                        '</select>';
            useCycleHtml = jQuery('<td onclick="noEditor()">'+useCycleHtml+'</td>');
            rowStr.append(useCycleHtml);

            var totalCapitalHtml = jQuery('<td>0</td>');
            rowStr.append(totalCapitalHtml);
            var usableCapitalHtml = jQuery('<td>0</td>');
            rowStr.append(usableCapitalHtml);
            {#var freezeCapitalHtml = jQuery('<td>0</td>');#}
            {#rowStr.append(freezeCapitalHtml);#}
            var profitHtml = jQuery('<td>0</td>');
            rowStr.append(profitHtml);
            var commissionRatioHtml = jQuery('<td>0</td>');
            rowStr.append(commissionRatioHtml);
            var commissionHtml = jQuery('<td>0</td>');
            rowStr.append(commissionHtml);

            var today = formatDate(new Date().getTime()).substring(0,11);
            var endDate = formatDate(addDate(today,30)).substring(0,11);
            var alertDate = formatDate(addDate(endDate,-10)).substring(0,11);

            var beginDateWidth = widthList[11];
            var beginDateHtml = jQuery('<td onclick="noEditor()">' +'<input type="text" style="width:'+String(beginDateWidth)+'px;" ' +
                'class="no-ediotr" value="'+today+'" disabled=true/>' + '</td>');
            rowStr.append(beginDateHtml);

            var operateTimesHtml = jQuery('<td>0</td>');
            rowStr.append(operateTimesHtml);

            var brokerNameWidth = widthList[13];
            var brokerNameHtml = jQuery('<td>' +'<input type="text" style="width:'+String(brokerNameWidth)+'px;" ' +
                'class="broker-name"/>' + '</td>');
            rowStr.append(brokerNameHtml);

            var strategy_list = [];
            var checkboxList = $(".editor" + "[type='checkbox']");
            checkboxList.each(function (key,value) {
                var strategy = $(value).attr('class').split(' ')[2];
                if (strategy_list.indexOf(strategy) == -1){
                    strategy_list.push(strategy);
            }
            });
            var strategyWidth = widthList[14];
            var strategyHtml = '';
            for (var i =0;i<strategy_list.length;i++){
                strategyHtml += '<label><input class="no-ediotr"  type="checkbox" ' +
                'disabled=true value="" >' + strategy_list[i]+ '</label><br/>';
            }
            strategyHtml = jQuery('<td onclick="noEditor()">' + strategyHtml + '</td>');
            rowStr.append(strategyHtml);

            var rcStrategyHtml = jQuery('<td>无</td>');
            rowStr.append(rcStrategyHtml);

            var strategyStatusHtml = jQuery('<td>停止交易</td>');
            rowStr.append(strategyStatusHtml);

            var cashWidth = 100;
            var cashHtml = jQuery('<td onclick="noEditor()">' +'<input type="text" style="width:'+String(cashWidth)+'px;" ' +
                'class="no-editor" value="1" disabled=true/>' + '</td>');
            rowStr.append(cashHtml);

            //var buttonWidth = widthList[15];
            {#var buttonHtml = jQuery('<td><button class="button" type="text" onclick="clear()" >重新结算</button></td>');#}
            {#rowStr.append(buttonHtml);#}

            var buttonWidth = widthList[18]+widthList[19];
            var buttonHtml = jQuery('<td colspan="2"><button class="button" style="width:'+String(buttonWidth)+'px;" type="text" onclick="submit()" >提交</button></td>');
            rowStr.append(buttonHtml);
            clientManageDataTable.data([], 'code');
            $("#clientManageDataTable").find('table > tbody').append(rowStr);
            $("#submit").show();
            var h = $(document).height()-$(window).height();
            $(document).scrollTop(h);
        }
        function addStrategy() {
            $(document).scrollTop(0);
            document.getElementById('light').style.display='block';
            document.getElementById('fade').style.display='block';
            $(document.body).css({
           "overflow-x":"hidden",
           "overflow-y":"hidden"
            });
        }
        function addStrategySubmit() {
            var strategy_name = $("#input-strategy-name").val();
            var delete_strategy_name = $("#delete-strategy-name").val()
            if (strategy_name == "" & delete_strategy_name=="" ){
                alert("请输入需添加的策略名或者需删除的策略名!");
                return;
            }
            if (strategy_name == "" & delete_strategy_name!="" ){
                var go = confirm("您确定要删除策略" + delete_strategy_name +"吗?请谨慎操作!!");
                if (go==false){
                    return;
                }
            }
            if (strategy_name != "" & delete_strategy_name!="" ){
                var go = confirm("您确定要添加策略"+strategy_name+",删除策略" + delete_strategy_name +"吗?请谨慎操作!!");
                if (go==false){
                    return;
                }
            }
            var strategy_list = [];
            var checkboxList = $(".editor" + "[type='checkbox']");
            checkboxList.each(function (key,value) {
                var strategy = $(value).attr('class').split(' ')[2];
                if (strategy_list.indexOf(strategy) == -1){
                    strategy_list.push(strategy);
            }
            });
            if (strategy_name != ""){
                if (strategy_list.indexOf(strategy_name) > -1){
                alert("该策略已经存在,无法添加!");
                return;
            }
            }
            if (delete_strategy_name !=""){
                if (strategy_list.indexOf(delete_strategy_name) == -1){
                alert("该策略不存在,无法删除!");
                return;
                }
            }

            $.ajax( {
                url:"/addStrategy",
                async:true,
                type:"POST",
                data:JSON.stringify({"strategy_name":strategy_name,"delete_strategy_name":delete_strategy_name}),
                success:function (result) {
                    if($.type(result)=="string"){
                        result = JSON.parse(result);
                    }
                    var message = result.message;
                    alert(message);
                    location.reload();
                }
            });

        }
        function addStrategyCancel() {
            document.getElementById('light').style.display='none';
            document.getElementById('fade').style.display='none';
             $(document.body).css({
               "overflow-x":"auto",
               "overflow-y":"auto"
             });
        }
        function changeInitCash(accountId){
            document.getElementById('light-cash').style.display='block';
            document.getElementById('fade-cash').style.display='block';
            var outputList=clientList.filter(
            function (item) {
                return (item["accountId"] == accountId);
            });
            var html = "        <p align=\"center\">请仔细核对后提交,提交后强刷账户更新收益<p>\n" +
                "        原本金:<input type=\"text\" class=\"form-control\" id=\"old-init-cash\">\n" +
                "        修改后本金:<input type=\"text\" class=\"form-control\" id=\"new-init-cash\">\n" +
                "        <div align=\"center\">\n" +
                "            <div class=\"btn-group btn-group-lg\" role=\"group\" aria-label=\"...\">\n" +
                "                <div class=\"btn-group\" role=\"group\">\n" +
                "                <button type=\"button\" class=\"btn btn-primary\" onclick=\"changeInitCashSubmit(\'"+accountId+"\')\">提交</button>\n" +
                "                </div>\n" +
                "                <div class=\"btn-group\" role=\"group\">\n" +
                "                <button type=\"button\" class=\"btn btn-primary\" onclick=\"changeInitCashCancel()\">取消</button>\n" +
                "                </div>\n" +
                "            </div>\n" +
                "        </div>";
            $("#light-cash").html(html);
            $("#old-init-cash").val(outputList[0]["initCash"]);
            $("#old-init-cash").attr("disabled",true);
            $(document.body).css({
           "overflow-x":"hidden",
           "overflow-y":"hidden"
            });
        }
        function changeInitCashSubmit(accountId) {
            var new_init_cash = $("#new-init-cash").val();
            if (new_init_cash== "" ){
                alert("请输入新的本金");
                return;
            }
            if ($.type(parseFloat(new_init_cash))!="number"){
                alert("请输入数字");
                return;
            }
            $.ajax({
                "url":"/editorClient",
                async:true,
                type:"POST",
                data:JSON.stringify({"init_cash":parseFloat(new_init_cash),"account_id":accountId}),
                dataType:"json",
                success:function (obj) {
                    if ($.type(obj) == "string"){
                        obj = JSON.parse(obj);
                    }
                    var message = obj.message;
                    alert(message);
                document.getElementById('light-cash').style.display='none';
                document.getElementById('fade-cash').style.display='none';
                 $(document.body).css({
                   "overflow-x":"auto",
                   "overflow-y":"auto"
                 });
                 location.reload();
                }
            })
        }
        function changeInitCashCancel() {
            document.getElementById('light-cash').style.display='none';
            document.getElementById('fade-cash').style.display='none';
             $(document.body).css({
               "overflow-x":"auto",
               "overflow-y":"auto"
             });
        }
        function noEditor() {

            window.alert("请先提交后再进行配置!");
        }
        function changeType(accountId) {
            var useType = $("."+accountId).find("option:selected").text();
            var today = formatDate(new Date().getTime()).substring(0, 11);
            var tomorrow = formatDate(addDate(today, 1)).substring(0, 11);
            var oneMonthAfter = formatDate(addDate(today, 30)).substring(0, 11);
            var oneMonthAfterAlert = formatDate(addDate(oneMonthAfter, -10)).substring(0, 11);
            var oneYearAfter = formatDate(addDate(today, 365)).substring(0, 11);
            var oneYearAfterAlert = formatDate(addDate(oneYearAfter, -10)).substring(0, 11);
            $("."+accountId+".beginDate").val(tomorrow);

        }


        function editorAccount(accountId) {
            var outputList=clientList.filter(
            function (item) {
                return (item["accountId"] == accountId);
            });
            clientManageDataTable.data(outputList, 'code');

            var buttonList = $(".button.editor");
            var hasEditoring = false;
            buttonList.each(function (key, value) {
                if ($(value).prop("disabled") == true) {
                    hasEditoring = true;
                    var className = $(value).attr('class').split(' ')[2];
                    window.alert("请先完成对" + className + "的编辑!");
                    return false;
                }

            });
            if (hasEditoring == true) {
                return;
            }
            var accountId = accountId;
            $(".editor." + accountId).removeAttr("disabled");
            $(".button." + accountId).attr("disabled", "true");
            $("#editor_to_show").show();
            var htmlStr = '<div align="center" id = "editor_to_show" >\n' +
                '\n' +
                '    <div class="btn-group btn-group-lg" role="group" aria-label="...">\n' +
                '\n' +
                '        <div class="btn-group" role="group">\n' +
                '        <button type="button" class="btn btn-primary" onclick="delAccount(\'' + accountId +
                '\')">删除该客户</button>\n' +
                '        </div>\n' +
                '\n' +
                '        <div class="btn-group" role="group">\n' +
                '        <button type="button" class="btn btn-primary" onclick="editorSubmit(\'' + accountId +
                '\')">提交</button>\n' +
                '        </div>\n' +
                '\n' +
                '       <div class="btn-group" role="group">\n' +
                '        <button type="button" class="btn btn-primary" onclick="changeInitCash(\'' + accountId +
                '\')">修改本金</button>\n' +
                '        </div>\n' +
                '\n' +
                '\n' +
                '        <div class="btn-group" role="group">\n' +
                '        <button type="button" class="btn btn-primary" onclick="cancel()">取消</button>\n' +
                '        </div>\n' +
                '        \n' +
                '\n' +
                '    </div>\n' +
                '</div>';
            $("#client_manage").append(htmlStr);
        }

        function selectStrategy(accountId,strategy,profit,useCycle) {

            if ($("." + accountId +"."+strategy+ "[type='checkbox']").is(':checked')) {
                if (useCycle=='正式用户' & profit>=10){
                    window.alert("收益超过10%，请先结算再绑定策略!");
                    $("." + accountId +"."+strategy+ "[type='checkbox']").prop("checked",false);
                }else{
                    window.alert("你已经为客户 " + accountId + " 绑定策略"+ strategy +"!!");
                }
            } else {
                window.alert("你已经为客户 " + accountId + " 解除策略" + strategy +"的绑定关系!!");
                //$("." + accountId +"."+strategy+ "[type='checkbox']").prop("checked",true);//很简单就不说了哦
                //$("." + accountId +"."+strategy+ "[type='checkbox']").prop({checked:true}); //map键值对
            }

        }

        function delAccount(accountId) {
            var go = window.confirm("你确定要删除客户" + accountId + "吗？");
            if (go == false) {
                return;
            }
            $.ajax({
                url: "/delClient",
                async: true,
                type: 'POST',
                data: JSON.stringify({'account_id': accountId}),
                dataType: 'json',
                success: function (result) {
                    var message = result.message;
                    alert(message);
                    refreshData();
                    location.reload();
                }
            });
        }

        function clearClient(accountId) {
            var go = window.confirm("你确定要给客户" + accountId + "重新结算吗？");
            if (go == false) {
                return;
            }
            $.ajax({
                url: "/clearClient",
                async: true,
                type: 'POST',
                data: JSON.stringify({'account_id': accountId}),
                dataType: 'json',
                success: function (result) {
                    var message = result.message;
                    alert(message);
                    refreshData();
                    {#location.reload();#}
                }
            });
        }

        function editorSubmit(accountId) {
            var alertStr = "配置如下:\n用户类型:";
            var useType = $("." + accountId).find("option:selected").text();
            alertStr += String(useType) + "\n";
            var openStrategy = '';
            var strategyList = '';
            var checkboxList = $("." + accountId + "[type='checkbox']");
            alertStr += "绑定策略:";
            checkboxList.each(function (key,value) {
                strategyList += $(value).attr('class').split(' ')[2]+",";
                if ($(value).is(':checked')){
                    alertStr += $(value).attr('class').split(' ')[2];
                    alertStr += ",";
                    openStrategy += "1,";
                }else{
                    openStrategy += "0,";
                }
            });
            strategyList = strategyList.slice(0,-1);
            openStrategy = openStrategy.slice(0,-1);
            if (alertStr.indexOf(',')>-1){
                alertStr = alertStr.slice(0,-1);
            }else{
                alertStr += "无";
            }
            alertStr += "\n";

            var cash = $("." + accountId + ".cash").val();

            try
            {
            var commission_ratio = parseFloat($("." + accountId + ".commission_ratio").val());
            }
            catch (e)
            {
            alert("请输入正确的提成比例!!!");
            }
            alertStr += "出手资金:" + cash + "元,小于1手按1手算\n";
            var go = window.confirm(alertStr);
            if (go == false) {
                return;
            }
            var beginDate = $(".beginDate." + accountId).val();
            var endDate = formatDate(addDate(beginDate, 365)).substring(0, 11);
            var alertDate = formatDate(addDate(endDate, -10)).substring(0, 11);


            $.ajax({
                url: "/editorClient",
                async: true,
                type: 'POST',
                data: JSON.stringify({
                    'account_id': accountId, 'use_type': useType, 'open_strategy': openStrategy, 'cash': cash,
                    'commission_ratio':commission_ratio,
                    'begin_date': beginDate, 'alert_date': alertDate, 'end_date': endDate, 'strategy_list':strategyList
                }),
                dataType: 'json',
                success: function (result) {
                    var message = result.message;
                    alert(message);
                    refreshData();
                    location.reload();
                }
            });
        }

        function cancel() {
            location.reload();
        }

        function submit() {
            var accountId = $(".account-id").val();
            if (accountId == '') {
                window.alert("账户id不能为空!");
                return;
            }
            var userName = $(".user-name").val();
            if (userName == '') {
                window.alert("用户名不能为空!");
                return;
            }
            var password = $(".password").val();
            if (password == '') {
                window.alert("密码不能为空!");
                return;
            }

            var brokerName = $(".broker-name").val();
            if (brokerName == '') {
                window.alert("券商名不能为空!");
                return;
            }

            var qsid = '';
            var brokerNameList = [];
            for (var i=0;i<brokerNameData.length;i++){
                brokerNameList.push(brokerNameData[i]['brokerName']);
            }
            if (brokerNameList.indexOf(brokerName)>-1){
                var index = brokerNameList.indexOf(brokerName);
                qsid = brokerNameData[index]['qsid'];
            }else if(brokerNameList.indexOf(brokerName.replace('证券',''))>-1){
                var index = brokerNameList.indexOf(brokerName.replace('证券',''));
                brokerName = brokerNameData[index]['brokerName'];
                qsid = brokerNameData[index]['qsid'];
            }else{
                window.alert("券商名称输入有误!");
                return;
            }

            var go = window.confirm("你确定要添加客户" + accountId + "吗？");
            if (go == false) {
                return;
            }
            if (accountList.indexOf(accountId) > -1){
                window.alert("该账户已经存在!")
                return;
            }

            var alertStr = "请仔细核对，添加后不允许更改:\n";

            alertStr += "账户id: " + accountId + "\n";
            alertStr += "用户名: " + userName + "\n";
            alertStr += "密码: " + password + "\n";
            alertStr += "券商名称: " + brokerName + "\n";

            var go = window.confirm(alertStr);
            if (go == false) {
                return;
            }
            $.ajax({
                url: "/addClient",
                async: true,
                type: 'POST',
                data: JSON.stringify({'account_id': accountId, 'user_name': userName,'password':password, 'broker_name': brokerName,'qsid':qsid}),
                dataType: 'json',
                success: function (result) {
                    var message = result.message;
                    alert(message);
                    $("#submit").hide();
                    refreshData();
                }
            });

        }

        $("#submit").hide();
        var clientManageDataTable = null;
        var accountList = [];
        var brokerNameData = [];
        var clientList = [];
        $.getJSON("/static/json/brokerName.json", function (data){
            brokerNameData = data;

      //显示处理后的数据
    });

        clientManageDataTable = jQuery("#clientManageDataTable").raytable({
            datasource: {data: [], keyfield: 'stock_code'},
            columns: [
                {field: "accountId", title: "账户"},
                {field: "userName", title: "用户名"},
                {field: "userType", title:"密/险"},
                {field: "initCash", title: "本金"},
                {field: "useCycle", title: "用户类型"},
                {field: "nowCash", title: "总资产"},
                {field: "usableCash", title: "可用资金"},
                {#{field: "marketValue", title: "市值"},#}
                {field: "profit", title: "收益(%)"},
                {field: "commission_ratio", title: "提成比例"},
                {field: "commission", title: "提成金额"},
                {#{ field: "renew", title: "续费"},#}
                {field: "beginDate", title: "开通日期"},
                {#{field: "endDate", title: "截止日期"},#}
                {#{field: "alertDate", title: "提醒续费日期"},#}
                {field: "operateTimes", title: "操作次数"},
                {field: "brokerName", title: "券商名称"},
                {field: "strategy", title: "策略"},
                {field:"rcStrategy",title:"RC策略(只读)"},
                {field:"status",title:"账户状态"},
                {field: "amount", title: "出手资金(元,最少按1手)"},
                {#{field: "clear", title: "结算"},#}
                {field: "editor", title: "编辑"}
            ],
            pagesize: 20,
            maxPageButtons: 5,
            rowNumbers: true
        });

        function refreshData() {
            $.ajax({
                url: "/clientManageData?account=001",
                async: true,
                success: function (result) {
                    var obj = JSON.parse(result);
                    clientList = obj.clientList;
                    var message = obj.message;
                    if (message!="正常"){
                        alert(message);
                    }
                    var userNameList = [];
                    for (var i=0;i<clientList.length;i++){
                        accountList.push(clientList[i]['accountId']);
                        userNameList.push(clientList[i]['userName']);
                    }

                    clientManageDataTable.data(clientList, 'stock_code');
                    var htmlStr = "";
                    for (var i=0;i<userNameList.length;i++){
                        htmlStr +=
                        "<label class=\"checkbox-inline\">" +
                        "<input class=\"user-name-checkbox\" type=\"checkbox\" id=\"inlineCheckbox1\" value=\"" + userNameList[i] +
                        "\">" + userNameList[i] +
                        "</label>";
                    }
                    $("#user_name_checkbox").html(htmlStr);
                    allIn(true);
                }
            })
        }

            refreshData();



</script>

</body>
</html>